package com.ecnu.web.controller.project;

import com.ecnu.common.constant.HttpStatus;
import com.ecnu.common.core.controller.BaseController;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.entity.SysRole;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.PageDomain;
import com.ecnu.common.core.page.TableDataInfo;
import com.ecnu.common.utils.OtherUtil;
import com.ecnu.system.domain.Project;
import com.ecnu.system.domain.dto.ProjectDTO;
import com.ecnu.system.domain.dto.ProjectForMyDTO;
import com.ecnu.system.domain.dto.ProjectListDTO;
import com.ecnu.system.service.IProjectService;
import com.ecnu.system.service.IProjectTeacherService;
import com.ecnu.system.service.IProjectUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "活动管理")
@RestController
@RequestMapping("/project")
@Validated//用来校验controller参数带@notblack类似的注解
public class ProjectController extends BaseController {
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IProjectUserService userService;
    @Autowired
    private IProjectTeacherService teacherService;

    /**
     * 活动列表
     *
     * @param listDTO
     * @return
     */
    @ApiOperation(value = "活动列表")
    @PostMapping("/list")
    public TableDataInfo list(@Valid @RequestBody ProjectListDTO listDTO) {
        LoginUser proUser = getProUser();

        //需要调整，添加搜索条件
        return projectService.ProjectList(listDTO, proUser);
    }

    
    @ApiOperation(value = "简介")
    @GetMapping("/brief")
    public AjaxResult brief(String id) {
        try {
            LoginUser loginUser = getProUser();
            return projectService.briefById(id, loginUser);
        } catch (Exception e) {
            logger.error("活动查询错误,错误id为："+id+"，\n具体内容:"+e.getMessage());
            return AjaxResult.error("活动查询错误", e.getMessage());
        }
    }

    private static LoginUser getProUser() {
        LoginUser loginUser = new LoginUser();
        //看情况是否需要优化--获取登录信息问题
        try {
            loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {

        }
        return loginUser;
    }

    /**
     * 后台管理
     *
     * @param listDTO
     * @return
     */
    @ApiOperation(value = "活动管理")
    @PostMapping("/projectList")
    @PreAuthorize("@ss.hasPermi('project:list')")
    public TableDataInfo projectList(@RequestBody ProjectListDTO listDTO) {
        try {
            LoginUser loginUser = getLoginUser();//获取当前登录用户信息
            List<SysRole> roles = loginUser.getUser().getRoles();//获取当前登录用户角色信息
            String name = roles.stream()
                    .anyMatch(role -> role.getRoleId() != 1 && role.getRoleId()!=2)
                    ? loginUser.getUser().getUserId().toString() : null;
            return projectService.allList(listDTO, name);
        } catch (Exception e) {
            logger.error("活动管理接口错误：\n" + e.getMessage());
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg(e.getMessage());
            return rspData;
        }
    }

    @ApiOperation(value = "删除活动")
    @PostMapping("/del")
    @PreAuthorize("@ss.hasPermi('project:del')")
    public AjaxResult delProject(@RequestBody String[] ids) {
        try {
            LoginUser loginUser = getLoginUser();
            List<Project> projects = Arrays.stream(ids)
                    .map(id -> {
                        Project project = new Project();
                        project.setId(id);
                        project.setDelFlag("2");
                        project.setUpdateUser(loginUser.getUserId().toString());
                        return project;
                    })
                    .collect(Collectors.toList());
            return projectService.updateBatchById(projects) ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
        } catch (Exception e) {
            logger.error("活动删除错误" + e.getMessage());
            return AjaxResult.error("删除失败");
        }
    }

    @ApiOperation(value = "活动明细")
    @GetMapping("/info")
    public AjaxResult info(String id) {
        try {
            return projectService.infoById(id);
        } catch (Exception e) {
            logger.error("活动查询错误,错误id为："+id+"，\n具体内容:"+e.getMessage());
            return AjaxResult.error("活动查询错误", e.getMessage());
        }
    }


    @ApiOperation(value = "编辑活动")
    @PostMapping("/edit")
    @PreAuthorize("@ss.hasPermi('project:edit')")
    public AjaxResult edit(@Valid @RequestBody ProjectDTO project) {
        LoginUser loginUser = getLoginUser();
        try {
            return projectService.edit(project, loginUser);
        } catch (Exception e) {
            logger.error("保存错误", e.getMessage());
            return AjaxResult.error("保存错误", e.getMessage());
        }
    }

    @ApiOperation(value = "我的活动")
    @PostMapping("/projectForMy")
//    @PreAuthorize("@ss.hasPermi('project:projectForMy')")
    public TableDataInfo projectForMy(@RequestBody ProjectForMyDTO project) {
        LoginUser loginUser = getLoginUser();
        return projectService.projectForMy(project, loginUser.getUser().getUserId().toString());
    }

    @ApiOperation(value = "获取活动成员")
    @GetMapping("/getProUser")
    public TableDataInfo getProUser(@NotBlank(message = "活动id不能为空") String id,
                                 String nickName,
                                 @Min(1) @RequestParam(defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "10") Integer pageSize) {
        Project project = projectService.getById(id);
        if (project == null) {
            return OtherUtil.tableError( "活动不存在");
        }
        PageDomain domain = new PageDomain();
        domain.setPageNum(pageNum);
        domain.setPageSize(pageSize);
        return userService.getProUser(id, nickName, domain);
    }
    @ApiOperation(value = "获取活动成员（导出）")
    @GetMapping("/getProUserExcel")
    public void getProUserExcel(@NotBlank(message = "活动id不能为空") String id, HttpServletResponse response) {
        Project project = projectService.getById(id);
        if (project == null) {
           throw new RuntimeException( "活动不存在");
        }

        userService.getProUserExcel(id,response,project);
    }

    @ApiOperation(value = "获取活动教师")
    @GetMapping("/getProTeacher")
    public TableDataInfo getProTeacher(@NotBlank(message = "活动id不能为空") String id,
                                    String nickName,
                                    @Min(1) @RequestParam(defaultValue = "1") Integer pageNum,
                                    @RequestParam(defaultValue = "10") Integer pageSize) {

        Project project = projectService.getById(id);
        if (project == null) {
            return OtherUtil.tableError( "活动不存在");
        }
        PageDomain domain = new PageDomain();
        domain.setPageNum(pageNum);
        domain.setPageSize(pageSize);
        return teacherService.getProUser(id, nickName,domain);
    }
}
